import cn.hutool.core.thread.NamedThreadFactory;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author brianxia
 * @version 1.0
 * @date 2021/12/23 16:59
 */
public class ThreadPoolDemo {

    public static String doSomething1(){
        try {
            Thread.sleep(1000L);
        } catch (InterruptedException e) {
            e.printStackTrace();
            return "456";
        }
        return "123";
    }

    @lombok.SneakyThrows
    public static void test1() {
        int processors = Runtime.getRuntime().availableProcessors();

        ThreadPoolExecutor threadPoolExecutor =
                new ThreadPoolExecutor(processors, processors * 2, 2, TimeUnit.SECONDS,
                        new LinkedBlockingQueue<>(10),
                        new NamedThreadFactory("mythread",false),
                        new ThreadPoolExecutor.CallerRunsPolicy());


        Future<String> submit = threadPoolExecutor.submit(ThreadPoolDemo::doSomething1);
        threadPoolExecutor.shutdownNow();
        //反射获取状态
        Class<ThreadPoolExecutor> threadPoolExecutorClass = ThreadPoolExecutor.class;
        Field ctl = threadPoolExecutorClass.getDeclaredField("ctl");
        ctl.setAccessible(true);
        AtomicInteger o = (AtomicInteger) ctl.get(threadPoolExecutor);
        Method runStateOf = threadPoolExecutorClass.getDeclaredMethod("runStateOf", int.class);
        runStateOf.setAccessible(true);


        String s = submit.get();
        System.out.println(s);

        Thread.sleep(5000L);

        int invoke = (int) runStateOf.invoke(threadPoolExecutor, o.get());
        System.out.println(invoke);
    }



    public static void main(String[] args) {
        test1();
    }
}
